import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 定义两个函数
def f1(x):
    return x**2  # y = x^2

def f2(x):
    return 3*x   # y = 3x

# 计算交点
def find_intersection(f, g, x_range):
    x = np.linspace(x_range[0], x_range[1], 1000)
    diff = f(x) - g(x)
    intersections = []
    for i in range(len(diff)-1):
        if diff[i] * diff[i+1] <= 0:
            x_root = x[i] - diff[i] * (x[i+1] - x[i]) / (diff[i+1] - diff[i])
            intersections.append(x_root)
    return intersections

# 计算两条曲线之间的面积
def area_between_curves(f, g, a, b):
    """
    计算函数f(x)和g(x)在区间[a,b]之间的面积
    """
    # 确保f(x) >= g(x)，否则取绝对值
    area = integrate.quad(lambda x: abs(f(x) - g(x)), a, b)
    return area

# 定义积分区间
x_range = [-1, 4]

# 求交点
intersections = find_intersection(f1, f2, x_range)
formatted_intersections = [f"{x:.8f}" for x in intersections]  # 保留8位小数
print(f"交点横坐标: {formatted_intersections}")

# 计算面积
area, error = area_between_curves(f1, f2, intersections[0], intersections[1])

print(f"两条曲线之间的面积为: {area:.6f}")

# 可视化
x = np.linspace(-1, 4, 1000)
y1 = f1(x)
y2 = f2(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y1, 'b-', label='$y = x^2$', linewidth=2)
plt.plot(x, y2, 'r-', label='$y = 3x$', linewidth=2)

plt.fill_between(x, y1, y2, where=(x >= intersections[0]) & (x <= intersections[1]), 
                 alpha=0.3, color='green', label='面积区域')
plt.xlabel('x')
plt.ylabel('y')
plt.title('两条曲线围成的图形面积')
plt.legend()
plt.grid(True)
plt.show()